<?php

namespace app\services\product\product;

use app\services\BaseServices;
use app\services\product\sku\StoreProductAttrValueServices;
use DateTime;
use DateTimeZone;

/**
 * TODO 虚拟商品同步 Services
 * Class SyncStoreProductServices
 * @package app\services\product\product
 */
class SyncStoreProductServices extends BaseServices
{

    public function getTiemstamp(){
        $microtime = microtime(true);
        $seconds = floor($microtime);
        $milliseconds = round(($microtime - $seconds) * 1000);
        $dateTime = DateTime::createFromFormat('U', $seconds, new DateTimeZone('Asia/Shanghai'));
        $dateTime->setTimezone(new DateTimeZone('Asia/Shanghai')); // 确保时区设置

        $timestamp = $dateTime->format('YmdHis') . sprintf('%03d', $milliseconds);
        return $timestamp;
    }
    public function getParams($params){
        $params["appId"] = "sKHXHcSX14";
        $params["appSecret"] = "CkVhxJEgbgNxjYSL";
//        $params["outOrderId"] = "xxxxxx";
//        $params["itemId"] = "xxxxx";
//        $params["amount"] = "1";
        $params["timestamp"] = $this->getTiemstamp();
       $signStr = $this->createLinkString($params);
       $sign = $this->md5On($signStr);
       return $signStr."&sign=".$sign;
   }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数
     * @return string 拼接后字符串
      */
    public function createLinkString($params) {

      $keys = array_keys($params);
      sort($keys);

      $prestr = "";

      for ($i = 0; $i < count($keys); $i++) {
          $key = $keys[$i];
          $value = $params[$key];
          if ($i == count($keys) - 1) {//拼接时，不包括最后一个&字符
              $prestr = $prestr . $key . "=" . $value;
          } else {
              $prestr = $prestr . $key . "=" . $value . "&";
          }
      }
      return $prestr;
    }


    /**
     * MD5指纹算法
     *
     * @param str
     * @return
     */
    public function md5On($str) {
      if ($str == null) {
          return null;
      }
      return md5($str);
    }

    /**
     * base64密文的AES解密
     * @param content base64密文
     * @param password 密钥
     * @return 解密后明文|false|string
     */
    public static function decrypt($data='需要解密的数据', $key='平台给的密钥') {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
    }

    /**
     * 商品同步
     * @return mixed
     */

    public function syncStoreProduct(){
        return $this->transaction(function () {
            /** @var StoreProductServices $storeProductServices**/
            $storeProductServices = app()->make(StoreProductServices::class);
            /** @var StoreProductAttrValueServices $storeProductAttrValueServices **/
            $storeProductAttrValueServices = app()->make(StoreProductAttrValueServices::class);
            $params = $this->getParams([]);
            $url = "http://123.56.251.130:8911/api/item/query?$params";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);
            curl_close($ch);
            $response = mb_convert_encoding($response, 'UTF-8', 'auto');
            $response = json_decode($response, true);
            // TODO 获取失败,走失败记录流程
            if ($response['code'] != "00") {
                return;
            }

            $dataList = $response['data'];

            foreach ($dataList as $data) {
                $storeProduct = $storeProductServices->getOne(['item_id' => $data['itemId']]);
                if (isset($storeProduct)) {
                    $storeProductServices->update($storeProduct['id'], ['store_name' => $data['itemName'], 'is_show' => $data['status'] == 0 ? 0 : $storeProduct['is_show']]);
                    $storeProductAttrValue = $storeProductAttrValueServices->getOne(['product_id' => $storeProduct['id'], 'type' => 0]);
                    $storeProductAttrValueServices->update($storeProductAttrValue['id'], [
                        'cost' => $data['price'],
                    ]);
                }
                else
                    $this->createStoreProduct($data);
            }

            return [$dataList];
        });
    }

    public function createStoreProduct($data){
        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        $storeProduct = [
            'sync_type' => 1,
            "item_id" => $data['itemId'],
            "disk_info" => "",
            "logistics" => ["1"],
            "freight" => 2,
            "postage" => 0,
            "recommend" => [],
            "presale_day" => 1,
            "presale" => 0,
            "is_limit" => 0,
            "limit_type" => 0,
            "limit_num" => 0,
            "vip_product" => 0,
            "custom_form" => [],
            "store_name" => $data['itemName'],
            "cate_id" => [41],
            "label_id" => [],
            "keyword" => "",
            "unit_name" => "个",
            "store_info" => "",
            "image" => "",
            "recommend_image" => "",
            "slider_image" => ["https://ttxzgz.gzsoft.fun/uploads/attach/2023/02/20230210/6db89d3eb8ee8c1dc97db1e4bd6be8f1.png"],
            "description" => "",
            "ficti" => 0,
            "give_integral" => 0,
            "sort" => 0,
            "is_show" => 0,
            "is_gift" => 0,
            "gift_price" => 0,
            "is_hot" => 0,
            "is_benefit" => 0,
            "is_best" => 0,
            "is_new" => 0,
            "is_good" => 0,
            "is_postage" => 0,
            "is_sub" => [],
            "recommend_list" => [],
            "params_list" => [],
            "virtual_type" => 3,
            "id" => 0,
            "spec_type" => 0,
            "is_virtual" => 1,
            "video_link" => "",
            "temp_id" => "",
            "attrs" => [
                [
                    "pic" => "https://ttxzgz.gzsoft.fun/uploads/attach/2023/02/20230210/6db89d3eb8ee8c1dc97db1e4bd6be8f1.png",
                    "price" => $data['price'],
                    "cost" => $data['price'],
                    "ot_price" => $data['itemFace'],
                    "stock" => 0,
                    "bar_code" => "",
                    "bar_code_number" => "",
                    "weight" => 0,
                    "volume" => 0,
                    "brokerage" => 0,
                    "brokerage_two" => 0,
                    "vip_price" => $data['price'],
                    "virtual_list" => [],
                    "coupon_id" => 0
                    ]
            ],
            "items" => [],
            "activity" => [
                "默认",
                "秒杀",
                "砍价",
                "拼团"
            ],
            "couponName" => [],
            "header" => [],
            "selectRule" => "",
            "coupon_ids" => [],
            "command_word" => "",
            "min_qty" => 1,
            "label_list" => [],
            "protection_list" => [],
            "type" => 0,
            "is_copy" => 0
        ];
        $storeProductServices->save(0, $storeProduct);
    }



}